package org.lds.hotkey.client.autoconfigure.component;

import lombok.extern.slf4j.Slf4j;
import org.lds.hotkey.client.common.ClientErrorEnum;
import org.lds.hotkey.common.model.dto.ResultDTO;
import org.lds.hotkey.common.util.AssertUtil;
import org.lds.hotkey.common.util.InetAddressUtil;
import org.lds.hotkey.common.util.ScheduledUtil;
import org.lds.hotkey.console.remote.ConsoleClient;
import org.lds.hotkey.console.remote.model.request.AppInstanceRegisterRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;

@Slf4j
@Order(Integer.MIN_VALUE)
public class AppInstanceRegisterRunner implements ApplicationRunner {

    @Value("${spring.application.name}")
    private String appName;

    @Value("${server.port}")
    private int port;

    @Autowired
    private ConsoleClient consoleClient;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        ScheduledUtil.defaultSyncClosableScheduled(() -> execute());
    }

    private void execute() {
        // app实例注册
        ResultDTO<Long> resultDTO = consoleClient.registerAppInstance(AppInstanceRegisterRequest.builder()
                .appName(appName)
                .ip(InetAddressUtil.getInetAddress().getHostAddress())
                .port(port)
                .build());
        AssertUtil.assertTrue(ResultDTO.isSuccess(resultDTO), ClientErrorEnum.APP_INSTANCE_REGISTER_FAIL);

        log.info("app实例注册成功");
        AppContext.appId = resultDTO.getData();
    }
}
